package make

import (
	"fmt"
	"strings"

	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/console"
	"github.com/spf13/cobra"
)

var CmdMakeController = &cobra.Command{
	Use:   "controller",
	Short: "Create api controller, exmaple: make controller v1/user",
	Run:   runMakeController,
	Args:  cobra.ExactArgs(1), // 只允许且必须传 1 个参数
}

func runMakeController(cmd *cobra.Command, args []string) {

	// 处理参数，要求附带 API 版本（v1 或者 v2）
	array := strings.Split(args[0], "/")

	if len(array) < 2 {
		console.Exit("api controller name format: v1/user")
	}

	// apiVersion 用来拼接目标路径
	// name 用来生成 cmd.Model 实例
	name := array[len(array)-1]
	model := makeModelFromString(name, array[len(array)-2])

	array[len(array)-1] = model.TableName

	// 将字符串切片转换为接口切片
	arrPath := make([]interface{}, len(array))
	for i, v := range array {
		arrPath[i] = v
	}

	s := ""

	for i := 0; i < len(array); i++ {
		s = s + "/%s"
	}

	path := "app/http/controllers/api" + s + "_controller.go"

	// 组建目标目录
	filePath := fmt.Sprintf(path, arrPath...)
	// 基于模板创建文件（做好变量替换）
	createFileFromStub(filePath, "controller", model)

	console.Success("请前往 routes/api.go 增加路由")
}
